package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头上的token
        String token = request.getHeader("authorization");

        //2、判断token是否为空
        if(StringUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败无权限");
        }

        //3、解析token
        Claims claims = tokenService.parseToken(token);

        //4、判断claims是否为空
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException("认证失败无权限");
        }
        //hutool转换类型
        Long userId = MapUtil.get(claims, "userId", Long.class);
        //3、将userid存入本地线程
        UserThreadLocal.set(userId);

        //4、放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //本地线程清理
        UserThreadLocal.remove();
    }
}
